//
//  FRQViewController.m
//  FRQBluetoothKit
//
//  Created by xuchunhai on 12/31/2020.
//  Copyright (c) 2020 xuchunhai. All rights reserved.
//

#import "FRQViewController.h"
#import <FRQBluetoothKit/FRQBluetoothManager.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import "DeviceConnectTableViewCell.h"
#import "DeviceConnectViewHeader.h"
#import "TabbarViewController.h"
#import "FRQCroppedImageViewController.h"
#import "FRQAboutTokenshowViewController.h"
@interface FRQViewController ()<FRQBluetoothManagerDelegate>

@property(nonatomic, strong) NSMutableArray *peripheralListArray;
@property(nonatomic, strong) NSMutableArray *advertisementDataArray;
@property(nonatomic, strong) IBOutlet UIBarButtonItem *stopConnectItem;
@property (nonatomic,strong) DeviceConnectViewHeader *viewHeader;
@property (nonatomic,strong) NSString *devNo;
@property (nonatomic,assign) Boolean isCheck;
@end

@implementation FRQViewController
- (DeviceConnectViewHeader *)viewHeader{
    if (nil==_viewHeader) {
        _viewHeader=skXibView(@"DeviceConnectViewHeader");
        [self.view addSubview:self.viewHeader];
        [_viewHeader mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.right.left.mas_equalTo(0);
            make.height.mas_equalTo(300);
        }];
        [_viewHeader.viewActivity startAnimating];
        @weakify(self)
        [[_viewHeader.btnBack rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
        [[_viewHeader.btnSearch rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [[FRQBluetoothManager shareManager] scanPeripherals];
        }];
    }
    return _viewHeader;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.viewHeader.backgroundColor=skUIColorFromRGB(0x1c1f2a);
    
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor=skUIColorFromRGB(0x1c1f2a);
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(330);
        make.bottom.mas_equalTo(self.mas_bottomLayoutGuideTop);
        make.left.right.mas_equalTo(0);
    }];
    if(self.typeShow==0){
        self.viewHeader.labTip0.text=@"Pair Device";
    }else{
        self.viewHeader.labTip0.text=@"Connect Bluetooth";
    }
    
    
    self.peripheralListArray = [NSMutableArray array];
    self.advertisementDataArray = [NSMutableArray array];
    
    [FRQBluetoothManager shareManager].delegate = self;

    [[FRQBluetoothManager shareManager] setFilterForDiscoverPeripherals:^BOOL(NSString * _Nonnull peripheralName, NSDictionary * _Nonnull advertisementData, NSNumber * _Nonnull RSSI) {
        return [peripheralName hasPrefix:@"TS"];
    } andFilterForConnectToPeripherals:^BOOL(NSString * _Nonnull peripheralName, NSDictionary * _Nonnull advertisementData, NSNumber * _Nonnull RSSI) {
        return YES;
    }];
    [[FRQBluetoothManager shareManager] closeAllPeripheralsConnection:^(id<FRBleAbility>  _Nonnull ability) {

    }];

    //蓝牙修改处  开始扫描
//    [[BlueManager shareInstance] startScan];
    
    if(self.bvalCount == 1){
        _viewHeader.btnBack.hidden = YES;
    }else{
        _viewHeader.btnBack.hidden = NO;
    }
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [[FRQBluetoothManager shareManager] scanPeripherals];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [[FRQBluetoothManager shareManager] cancelScan];
    //蓝牙修改处  停止扫描
//    [[BlueManager shareInstance] stopScan];
}
-(IBAction)onCancelAllConnection:(UIBarButtonItem *)barItem{
    
    [[FRQBluetoothManager shareManager] closeAllPeripheralsConnection:^(id<FRBleAbility>  _Nonnull ability) {
        self.stopConnectItem.enabled = NO;
    }];
}

#pragma mark -- FRQBluetoothManagerDelegate
-(void)onBLEManagerCancelScan:(id<FRBleAbility>)ability{
    
    
}

-(void)onBLEManagerDiscoverPeripheral:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral advertisement:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if(self.typeShow == 1 && !isNilString(skDevice.devNo)){
        if([peripheral.name isEqualToString:skDevice.devNo]){
            [self.peripheralListArray removeAllObjects];
            [self.advertisementDataArray removeAllObjects];
            [self.peripheralListArray addObject:peripheral];
            
            [self.advertisementDataArray addObject:advertisementData];
            
            [self.tableView reloadData];
        }
    }else{
        if (![self.peripheralListArray containsObject:peripheral]) {
            
            [self.peripheralListArray addObject:peripheral];
            
            [self.advertisementDataArray addObject:advertisementData];
            
            [self.tableView reloadData];
        }
    }
    
}

-(void)onBLEManagerConnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    
    
    if (error) {
//        MBProgressHUD *toastHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        toastHUD.mode = MBProgressHUDModeText;
        
//        toastHUD.label.text = [NSString stringWithFormat:@"蓝牙设备%@，连接失败<%@>！！",peripheral.name,error.localizedDescription];
//        [toastHUD hideAnimated:YES afterDelay:5.0];
//        self.stopConnectItem.enabled = NO;
    }
    else{
//        self.stopConnectItem.enabled = YES;
//        toastHUD.label.text = [NSString stringWithFormat:@"蓝牙设备%@已连接成功！！",peripheral.name];
//        [toastHUD hideAnimated:YES afterDelay:3.0];
        if(self.typeShow==0){//链接设备成功
            if(self.isCheck){
                [self appDeviceAdd:peripheral];
            }
        }else{//这个是升级OTA链接设备成功
            if(self.isCheck){
                self.isCheck=NO;
                if(self.typeShow == 1){
                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:3] animated:YES];
                }else{
                    for(UIViewController *vc in self.navigationController.viewControllers){
                        if([vc isKindOfClass:[FRQAboutTokenshowViewController class]]){
                            [self.navigationController popToViewController:vc animated:YES];
                        }
                    }
                }
            }
        }
    }
    
}
-(void)appDeviceAdd:(CBPeripheral *)peripheral{
    NSLog(@"devNo==%@",self.devNo);
    self.isCheck=NO;
    
    NSDictionary *dic=@{@"devNo":[NSString stringWithFormat:@"%@",self.devNo],
                        @"devName":peripheral.name,
                        @"mac":@"",
                        @"uuid":peripheral.identifier
    };
    
    
    [skNetTools skPOSTWithURL:[NSString stringWithFormat:@"%@%@",skURL,@"app/device/add"] parameters:dic cachePolicy:0 callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        NSLog(@"数据=%@",responseObject);
        skNetModel *model=responseObject;
        if(model.code==200){
            CustomTabBarViewController *rootView=[[CustomTabBarViewController alloc] init];
            [[[UIApplication sharedApplication] delegate] window].rootViewController=rootView;
        }else{
            [SkToast SkToastShow:model.msg];
        }
    }];
}
-(void)onBLEManagerStateChange:(id<FRBleAbility>)ability{
    
//    [MBProgressHUD hideHUDForView:self.view animated:NO];
//    MBProgressHUD *toastHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    toastHud.mode = MBProgressHUDModeText;
    switch (ability.state) {
        case FRQManagerStateUnsupported:
        {
//            toastHud.label.text = @"请检查你蓝牙使用权限或检查设备问题";
        }
            break;
        case FRQManagerStateUnauthorized:
        {
//            toastHud.label.text = @"蓝牙设备暂无法使用，请在设置中授权";
        }
            break;
        case FRQManagerStatePoweredOff:
        {
//            toastHud.label.text =@"请打开蓝牙";
            
            [[FRQBluetoothManager shareManager] cancelScan];
        }
            break;
        case FRQManagerStatePoweredOn:
        {
//            toastHud.label.text = @"蓝牙已打开";
            //scan
            [[FRQBluetoothManager shareManager] scanPeripherals];
        }
            break;
        default:
            break;
    }
//    [toastHud hideAnimated:YES afterDelay:5.0];
    
}

-(void)onBLEManagerDisconnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    
//    self.stopConnectItem.enabled = NO;
//
//    [MBProgressHUD hideHUDForView:self.view animated:NO];
//
//    MBProgressHUD *toastHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    toastHUD.mode = MBProgressHUDModeText;
//    toastHUD.label.text = [NSString stringWithFormat:@"蓝牙设备%@已断开！！",peripheral.name];
//    if (error) { //异常断开设备连接
//        toastHUD.detailsLabel.text = error.localizedDescription;
//    }
//    [toastHUD hideAnimated:YES afterDelay:3.0];
    
}

// OTA升级阶段回调
-(void)onBLEManagerBeginUpdateOTA:(id<FRBleAbility>)ability{
    NSLog(@"55555");
    self.stopConnectItem.enabled = YES;
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    progressHUD.label.text = @"Ready to upgrade...";
    progressHUD.mode = MBProgressHUDModeText;
    [progressHUD hideAnimated:YES afterDelay:2.0];
    
}

-(void)onBLEManagerUpdateOTA:(id<FRBleAbility>)ability progress:(double)aProgress{
    NSLog(@"6666666");
    MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
    if (!progressHUD) {
        progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    progressHUD.label.text = @"OTA is being upgraded";
    progressHUD.detailsLabel.text = [NSString stringWithFormat:@"Current progress %.f %%, please wait...",aProgress];
    progressHUD.mode = MBProgressHUDModeAnnularDeterminate;
    progressHUD.progress = aProgress/100.0;
    
    self.stopConnectItem.enabled = NO;
}

-(void)onBLEManagerUpdateOTAFinish:(id<FRBleAbility>)ability error:(NSError *)error{
    NSLog(@"888888888");
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    self.stopConnectItem.enabled = YES;
    
    //alert
    NSString *alertMsg = error?error.localizedDescription:@"Device upgrade succeeded";
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"warn" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
    [alertCtrl addAction:[UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([alertMsg isEqualToString:@"The Bluetooth device is not authorized, please enable it in the Settings and try again"]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }else if([alertMsg isEqualToString:@"The Bluetooth device is turned off. Turn it on and try again"]){
            NSString * urlString = @"App-prefs:root=Bluetooth";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
        }
    }]];
    [self presentViewController:alertCtrl animated:YES completion:^{
        
    }];
    
}

#pragma mark -UIViewController 方法

-(void)updateOTAToPeripheral:(CBPeripheral *)peripheral{
    
    //开始OTA升级
    NSString *otaBinDataPath = [[NSBundle mainBundle] pathForResource:@"jyble_sdk" ofType:@"bin"];
    NSData *otaBinData = [NSData dataWithContentsOfFile:otaBinDataPath];
    [[FRQBluetoothManager shareManager] startConnect:peripheral];
    
}

#pragma mark -table委托 table delegate
#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     return self.peripheralListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    static NSString *cellIdentifier = @"DeviceConnectTableViewCell";
    DeviceConnectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = skXibView(@"DeviceConnectTableViewCell");
        @weakify(self)
        [[cell.btnPair rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            self.isCheck=YES;
            CBPeripheral *peripheral = [self.peripheralListArray objectAtIndex:indexPath.row];
            //蓝牙修改处  连接蓝牙 搜索服务特性
//            [[BlueManager shareInstance] selectPeripheral:peripheral];
            if(self.typeShow==0){
                NSDictionary *dictAd=[self.advertisementDataArray objectAtIndex:indexPath.row];
                
                self.devNo=[NSString stringWithFormat:@"%@",[dictAd objectForKey:@"kCBAdvDataLocalName"]];
                
                [self updateOTAToPeripheral:peripheral];
            }else{
               [self updateOTAToPeripheral:peripheral];
            }
        }];
    }
    cell.contentView.backgroundColor=skUIColorFromRGB(0x1c1f2a);
    
    CBPeripheral *peripheral = [self.peripheralListArray objectAtIndex:indexPath.row];
    
    cell.labName.text = peripheral.name?:@"N/A";
    if(self.typeShow==0){
        cell.imageIcon.image=[UIImage imageNamed:@"device_ico_menu"];
        [cell.btnPair setTitle:@"Pair" forState:(UIControlStateNormal)];
    }else{
        cell.imageIcon.image=[UIImage imageNamed:@"bluetooth_ico"];
        [cell.btnPair setTitle:@"Connect" forState:(UIControlStateNormal)];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    
    
}

@end
